/*
 * @Author: fanjs
 * @Date: 2025-01-08 00:03:50
 * @Description: 配置文件
 */
import { config as loadEnv } from 'dotenv';
import { join } from 'path';
import { ConfigType } from '../types/global';

// 加载环境变量
loadEnv({
  path: join(process.cwd(), `.env.${process.env.NODE_ENV || 'development'}`)
});

// 配置验证
function validateConfig() {
  if (process.env.NODE_ENV === 'production') {
    if (!process.env.JWT_SECRET) {
      throw new Error('JWT_SECRET must be set in production');
    }
    if (!process.env.WX_APP_ID || !process.env.WX_APP_SECRET) {
      throw new Error('WX_APP_ID and WX_APP_SECRET must be set in production');
    }
  }
}

// 创建配置对象
const config: ConfigType = {
  environment: process.env.NODE_ENV || 'development',
  port: Number(process.env.PORT) || 3000,
  connectDB: process.env.CONNECT_DB === 'true',
  apiPrefix: process.env.API_PREFIX || '/api',
  database: {
    dbName: process.env.DB_NAME || 'db_money',
    host: process.env.DB_HOST || '127.0.0.1',
    port: Number(process.env.DB_PORT) || 3306,
    username: process.env.DB_USERNAME || 'root',
    password: process.env.DB_PASSWORD || '',
    force: process.env.DB_FORCE === 'true',
    logging: process.env.DB_LOGGING === 'true' ? (sql: string) => console.log(sql) : false
  },
  security: {
    secretKey: process.env.JWT_SECRET || 'development-secret-key',
    expiresIn: Number(process.env.JWT_EXPIRES_IN) || 60 * 60 * 24 * 7
  },
  wx: {
    appID: process.env.WX_APP_ID || '',
    appSecret: process.env.WX_APP_SECRET || '',
    loginUrl: `https://api.weixin.qq.com/sns/jscode2session?appid=${process.env.WX_APP_ID}&secret=${process.env.WX_APP_SECRET}&js_code=%s&grant_type=authorization_code`
  },
  cors: {
    origin: process.env.CORS_ORIGIN || 'http://localhost:8080'
  },
  log: {
    level: process.env.LOG_LEVEL || 'info'
  },
  timezone: process.env.TZ || 'Asia/Shanghai',
};

// 验证配置
validateConfig();

export default config;